using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using OpenIddict.Server.AspNetCore;

namespace Net8.Identity.Server.Pages
{
    public class LogoutModel : PageModel
    {
        private readonly ILogger<LogoutModel> _logger;
        
        public LogoutModel(ILogger<LogoutModel> logger)
        {
            _logger = logger;
        }
        
        public void OnGet()
        {

        }
        
        public async Task<IActionResult> OnPostAsync(string confirm)
        {

            
            if (confirm == "Yes")
            {
                try
                {
                    // 清除本地Cookie认证
                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    
                    // 执行OpenIddict服务器登出
                    return SignOut(
                        authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                        properties: new AuthenticationProperties
                        {
                            RedirectUri = "/"
                        });
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "登出过程中发生错误");
                    return Page();
                }
            }
            
            // 如果用户取消或其他情况，重定向到首页
            return Redirect("/");
        }
    }
}
